export function parseMysql(sql) {
    // 去除注释
    sql = sql.replace(/--.*$/gm, '');

    // 提取表名
    let tableNameMatch = sql.match(/CREATE TABLE (\w+)/);
    let tableName = tableNameMatch ? tableNameMatch[1] : '';

    // 提取表注释
    let tableCommentMatch = sql.match(/COMMENT='(.*)'/);
    let tableComment = tableCommentMatch ? tableCommentMatch[1] : '';

    // 提取主键
    let primaryKeyMatch = sql.match(/PRIMARY KEY \((\w+)\)/);
    let primaryKey = primaryKeyMatch ? primaryKeyMatch[1] : '';

    const colStr = getColStr(sql)
    // 提取字段信息
    let columns = []
    const regexMatch = parseMysqlColByRegex(colStr);
    columns.push(...regexMatch)
    return {
        tableName,
        tableComment,
        primaryKey,
        columns
    };
}

/**
 * 对于 建表语句中的小数 decimal(5,2)这种错误分割的情况进行处理
 * @param array 要处理的数据
 * @returns {*}
 */
export function specialHandler(array) {
    for(let i = array.length - 1; i >= 0; i--) {
        let currentItem = array[i];
        if(/^\d/.test(currentItem)) {  // 使用正则表达式判断是否以数字开头
            let prevItem = array[i - 1];
            array[i - 1] = prevItem + ',' + currentItem;
            array.splice(i, 1);
        }
    }
    return array;
}

export function parseMysqlColByRegex(colStr) {
    let split = colStr.split(',');
    split = specialHandler(split)
    let columns = [];

    split.forEach(item => {
        item = item.toLowerCase()
        if (!item.includes("primary key")) {
            const colSplit = item.replaceAll('\n', '')
                .trim()
                .split(" ");
            let comment = ''
            if (colSplit[colSplit.length - 2] === 'comment') {
                comment = colSplit[colSplit.length - 1]
            }
            columns.push({
                name: colSplit[0],
                type: colSplit[1],
                comment
            });
        }
    })
    // // let fieldInfoMatches = colStr.matchAll(/(\w+)\s+([\w\(\)]+)\s+.*?COMMENT\s+'(.*)'/g);
    // let fieldInfoMatches = colStr.matchAll(/(\w+)\s+([\w\(\)]+)\s+.*?(?:COMMENT\s+'(.*?)')?/g);
    //
    // for (let match of fieldInfoMatches) {
    //     console.log(match, 'match')
    //     let comment = ''
    //     if (match[match.length - 2].toLowerCase() === 'comment') {
    //         comment = match[match.length - 1]
    //     }
    //     columns.push({
    //         name: match[1],
    //         type: match[2],
    //         comment
    //     });
    // }
    return columns
}

export function getColStr(sql) {
    const from = sql.indexOf('(') + 1
    const to = sql.lastIndexOf(')')
    return sql.substring(from, to);
}

export function beautifySQL(sql) {
    // 增加换行和缩进
    sql = sql.replace(/SELECT /ig, '\n  SELECT \n\t ')
        .replace(/INSERT /ig, '\n  INSERT ')
        .replace(/UPDATE /ig, '\n  UPDATE \n\t')
        .replace(/DELETE /ig, '\n  DELETE \n\t')
        .replace(/FROM /ig, '\n  FROM ')
        .replace(/INTO /ig, ' INTO ')
        .replace(/SET /ig, '\n  SET \n\t ')
        .replace(/WHERE /ig, '\n  WHERE ')
        .replace(/AND /ig, '\n\t  AND ')
        .replace(/OR /ig, '\n\t  OR ')
        .replace(/VALUES /ig, '\n  VALUES ')
        .replace(/OR /ig, '\n\t  OR ')
        .replace(/,/ig, ',\n\t');

    // 处理条件中的括号和空格
    sql = sql.replace(/WHERE \(/ig, '\n  WHERE (')
        .replace(/AND \(/ig, '\n\t  AND (')
        .replace(/OR \(/ig, '\n\t  OR (')
        .replace(/\( /ig, '(').replace(/ \)/g, ')');

    // 使每个 JOIN 的表单独起一行
    sql = sql.replace(/LEFT JOIN /ig, '\n  LEFT JOIN ')
        .replace(/RIGHT JOIN /ig, '\n  RIGHT JOIN ')
        .replace(/INNER JOIN /ig, '\n  INNER JOIN ');

    return sql;
}
